package com.topisv.tms.service.zto;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.topisv.tms.entity.Consignor;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ExpressConfigure;
import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.repository.ExpressConfigureDao;
import com.topisv.tms.service.ConsignorService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.WarehouseAddressService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.vo.PackItems;
import com.topisv.tms.service.vo.PrinterModel;
import com.topisv.tms.service.vo.PrinterStyleType;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.FileOperation;
import com.topisv.tms.utils.PrintModelUtil;
import com.topisv.tms.utils.print.PackFormUtil;

/**
 * @author tinsang
 */
@Component
public class ZTOEbillService {

    @Autowired
    private ConsignorService        consignorService;

    @Autowired
    private CustomersService        customersService;

    @Autowired
    private ExpressConfigureDao     expressConfigureDao;

    @Autowired
    private WorkOrderService        workOrderService;
    
    @Autowired
	private WorkTaskService workTaskService;

    @Autowired
    private WarehouseAddressService warehouseAddressService;
   
    @Autowired
	private EdiOrderItemService ediOrderItemService;

    /**
     * @param listEdiOrder
     * @param workTask
     * @return
     * @throws IOException
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    public List<PrinterStyleType> getZTOOrderAndMailno(List<EdiOrder> listEdiOrder, WorkTask workTask,
                                                       ExpressStyle expressStyle) throws Exception {
        final List<ZTOOrderBean> listZTOOrderBean = Lists.newArrayList();
        for (EdiOrder ediOrder : listEdiOrder) {
            ZTOOrderBean bean = new ZTOOrderBean();
            bean.setPaiuOrderId(ediOrder.getOrdeno());
            bean.setReceiverCity(ediOrder.getProvna() + "," + ediOrder.getCityna() + "," + ediOrder.getDistna());
            bean.setReceiver2Pro(ediOrder.getProvna());
            bean.setReceiver2City(ediOrder.getCityna());
            bean.setReceiver2Dist(ediOrder.getDistna());
            bean.setReceiverName(ediOrder.getRecena());
            bean.setReceiverAddress(ediOrder.getAddres());
            bean.setReceiverMobile(ediOrder.getMobile());
            bean.setReceiverPhone(ediOrder.getTeleph());

            WarehouseAddress warehouseAddres = warehouseAddressService.findByWarehouseCode(ediOrder.getWarehouseCode());
            bean.setSenderCity(warehouseAddres.getProvName() + "," + warehouseAddres.getCityName() + ","
                               + warehouseAddres.getDistName());
            bean.setSender2Pro(warehouseAddres.getProvName());
            bean.setSender2City(warehouseAddres.getCityName());
            bean.setSender2Dist(warehouseAddres.getDistName());
            bean.setSenderName(warehouseAddres.getContact());
            bean.setSenderMobile(warehouseAddres.getMobile());
            bean.setSenderAddress(warehouseAddres.getAddress());
            listZTOOrderBean.add(bean);
        }
        final String warehouseCode = workTask.getWarehouseCode();
        ExpressConfigure expressConfigure = expressConfigureDao.findByWarehouseAndCompany(warehouseCode, "ZTO");
        final String partner = expressConfigure.getAccount();
        final String pwd = expressConfigure.getPassword();
        ZTOUtils.submitBatch(listZTOOrderBean, partner, pwd);

        Map<String, ZTOOrderBean> mapReturn = Maps.newHashMap();
        for (ZTOOrderBean bean : listZTOOrderBean) {
            mapReturn.put(bean.getPaiuOrderId(), bean);
        }
        List<PrinterStyleType> printerList = Lists.newArrayList();
        for (EdiOrder ediOrder : listEdiOrder) {
            WorkOrder workOrder = workOrderService.loadOrder(ediOrder.getBatchTaskCode(), ediOrder.getOrdeno());
            ZTOOrderBean bean = mapReturn.get(ediOrder.getOrdeno());
            //workOrder.setEbillNo(bean.getZtoMailno());
            // 设置打印状态，写入快递单号数据
            workOrderService.setPrintStatus(workOrder.getOrder().getOrdeno(),
                bean.getZtoMailno(),
                expressStyle.getLogisticsCompany().getCompanyCode());
            ediOrder.setMailNo(bean.getZtoMailno());
            ediOrder.setCacode(expressStyle.getLogisticsCompany().getCompanyCode());
            ediOrder.setCaname(expressStyle.getLogisticsCompany().getCompanyName());
            ediOrder.setToShortAddress(bean.getMaker());
            ediOrder.setMessage(bean.getSitename());
            PrinterStyleType p = getPrinterStyleType(ediOrder, bean, workOrder, expressStyle);
            printerList.add(p);
        }
        return printerList;
    }

    private PrinterStyleType getPrinterStyleType(EdiOrder ediOrder, ZTOOrderBean bean, WorkOrder workOrder,
                                                 ExpressStyle expressStyle) throws Exception {
        PrinterModel printerModel = getExpressStyleModel(ediOrder, bean, workOrder);
        return getPrinterStyleType(printerModel, expressStyle);
    }

    /**
     * @param ediOrder
     * @param index
     * @return
     */
    private PrinterModel getExpressStyleModel(EdiOrder ediOrder, ZTOOrderBean bean, WorkOrder workOrder) {
        String ordeno = ediOrder.getOrdeno();
        
        WorkTask workTask=this.workTaskService.loadTaskByCode(ediOrder.getBackupTaskCode());
        
        // 快递单
        PrinterModel pm = new PrinterModel();
        //add by LiBin 2016/07/25 添加操作人 
        ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        if (null!=curUser) {
            pm.setOperator(curUser.username);
        }
        
        if (!"MID".equals(ediOrder.getCustomerCode())) {
            Customers customers = customersService.findByCustomerCode(ediOrder.getCustomerCode());
            Consignor consignor = consignorService.findCustomersId(customers.getId());
            // 寄件人信息
            if (consignor != null) {
                pm.setFromAddress(consignor.getAddress());
                pm.setFromName(consignor.getName());
                pm.setFromPhone(consignor.getPhone());
                pm.setFromMobile(StringUtils.isEmpty(consignor.getMobile()) ? consignor.getPhone() : consignor.getMobile());
                pm.setFromCompany(consignor.getAddress());
                pm.setFromCity(consignor.getCity());
                pm.setFromTowns(consignor.getDistrict());
                pm.setFromProvince(consignor.getProvince());
            }
        } else {
            pm.setFromAddress(bean.getSenderAddress());
            pm.setFromName(bean.getSenderName());
            pm.setFromMobile(StringUtils.isEmpty(bean.getSenderMobile()) ? bean.getSenderPhone() : bean.getSenderMobile());
            pm.setFromProvince(bean.getSender2Pro());
            pm.setFromCity(bean.getSender2City());
            pm.setFromTowns(bean.getSender2Dist());
        }
        pm.setFromno(ediOrder.getFromno());
        pm.setRankno(workOrder.getRankno());
        //pm.setTaskName(ediOrder.getBatchTaskCode() + "_" + ediOrder.getBackupTaskCode() + "_" + workTask.getOrderQty() + "_" + index);
        //update by LiBin 2016/07/25 添加显示信息 
        pm.setTaskName(new StringBuilder().append(ediOrder.getBatchTaskCode()).append("_").append(ediOrder.getBackupTaskCode()).append("_").append(workTask.getOrderQty()).append("_").append(workOrder.getRankno()).append(workOrder.getPrintFlag()>0?"_C"+(workOrder.getPrintFlag()+1):"").toString());

        pm.setOriginCode(ediOrder.getOriginCode());
        // 收件人信息
        pm.setToAddress(bean.getReceiverAddress());
        pm.setToName(bean.getReceiverName());
        pm.setToMobile(StringUtils.isEmpty(bean.getReceiverMobile()) ? bean.getReceiverPhone() : bean.getReceiverMobile());
        pm.setOrdeno(ordeno);
        pm.setTitleName(bean.getSitename());
        pm.setPayTime(getYYYYDDMM());
        pm.setExpressNo(ediOrder.getMailNo());
        // 大头笔
        pm.setShortAddress(ediOrder.getToShortAddress());
        List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(ediOrder.getCustomerCode(), ordeno);
		List<PackItems> packItems = new ArrayList<PackItems>();
		int orderItems = ediOrderItems.size()>3?3:ediOrderItems.size();
		int tempTotol=0;//计算一个订单包含的商品总数
		for (int j = 0; j < orderItems; j++) {
			EdiOrderItem ediOrderItem = ediOrderItems.get(j);
			PackItems packItem = new PackItems();
			packItem.setPrice(ediOrderItem.getPri() + "");
			packItem.setPay(ediOrderItem.getPay() + "");
			packItem.setDis(ediOrderItem.getDis() + "");
			packItem.setAmo(ediOrderItem.getAmo() + "");
			packItem.setNumber(ediOrderItem.getQty() + "");
			tempTotol+=ediOrderItem.getQty();
			packItem.setItemName(ediOrderItem.getNam());
			packItem.setPromotion(ediOrderItem.getPro() + "");
			packItem.setFormat(ediOrderItem.getSiz());
			packItem.setSkuNumber(ediOrderItem.getSku());// 货号
			packItem.setItemCode(ediOrderItem.getSku());// 货号
			packItem.setArticleNumber(ediOrderItem.getArticleNumber());
			packItems.add(packItem);
		}
		if(ediOrderItems.size()>3){
			for(int j=3;j<ediOrderItems.size();j++){
				EdiOrderItem ediOrderItem = ediOrderItems.get(j);
				tempTotol+=ediOrderItem.getQty();
			}
		}
		pm.setTotalSkuNumber(tempTotol+"");
		pm.setPackItems(packItems);
        return pm;
    }

    /**
     * yyyy年MM月dd日
     * 
     * @return
     */
    private String getYYYYDDMM() {
        DateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(new Date());
    }

    /**
     * @param printerModel
     * @param expressStyle
     * @return
     * @throws Exception
     */
    private PrinterStyleType getPrinterStyleType(PrinterModel printerModel, ExpressStyle expressStyle) throws Exception {
        String contentString = null;
        PrinterStyleType printerStyleType = new PrinterStyleType();
        String expressContent = FileOperation.readerContent(expressStyle.getStyleContent());// 转化的时候
        if ("normal".equals(expressStyle.getType())) {
            contentString = PrintModelUtil.replaceParams(expressContent, printerModel);
        } else if ("mail".equals(expressStyle.getType())) {
            contentString = PackFormUtil.replaceParams(expressContent, printerModel);
        }
        contentString = contentString.replace("'", "\\'").replaceAll("\"", "'");
        printerStyleType.setContent(contentString);
        printerStyleType.setCompanyCode(expressStyle.getLogisticsCompany().getCompanyCode());
        printerStyleType.setCompanyName(expressStyle.getLogisticsCompany().getCompanyName());
        printerStyleType.setTaskName(printerModel.getTaskName());
        printerStyleType.setRankno(printerModel.getRankno());
        printerStyleType.setOrdeno(printerModel.getOrdeno());
        printerStyleType.setTime(printerModel.getPayTime());
        printerStyleType.setFromno(printerModel.getFromno());
        printerStyleType.setExpressNo(printerModel.getExpressNo());
        return printerStyleType;
    }
}
